//路由
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const md5 = require('md5');
const luYou = express.Router();
const houTai = require('./houTai.js');
const shuJuKu = require(path.resolve('moKuai/shuJuKu.js'));
const qianTai = require('./qianTai.js');
const wsFuWu = require('./wsFuWu.js');

wsFuWu();

let laiYuan = 'http://localhost:3000'; 
//fetch的credentials为'include'时候 "Access-Control-Allow-Origin"不能为"*"

//允许跨域
luYou.all("*", function(qingQiu, xiangYing, jieZhe) {
	xiangYing.header("Access-Control-Allow-Origin", laiYuan);
	xiangYing.header("Access-Control-Allow-Headers", "content-type");
	xiangYing.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
	xiangYing.header("Access-Control-Allow-Credentials", "true");
	if (qingQiu.method.toLowerCase() == 'options')
		xiangYing.send(200); //让options尝试请求快速结束
	else jieZhe();
});
//静态目录
luYou.use(express.static('jingTai'));
//cookie解析
luYou.use(cookieParser());
//前台路由
luYou.use(qianTai);
//登录
luYou.get(`/dengLu`, async function(qingQiu, xiangYing) {
	let yongHu = await shuJuKu.chaYongHu();
	let qingQiuMiMa = qingQiu.query.miMa || '';
	let md5MingZi = md5(yongHu[0].mingZi);
	let md5Md5MiMa = md5(yongHu[0].miMa);
	let md5QingQiuMiMa = md5(qingQiuMiMa);
	if (qingQiu.query.mingZi != yongHu[0].mingZi) {
		xiangYing.send(`用户名不存在`)
	} else if (md5QingQiuMiMa == yongHu[0].miMa) {
		xiangYing.cookie('yanZheng', md5MingZi + md5Md5MiMa, {
			expires: new Date(Date.now() + 9000000)
		});
		xiangYing.cookie('mingZi',yongHu[0].mingZi, {
			expires: new Date(Date.now() + 9000000)
		})
		xiangYing.send(`登录成功`)
	} else {
		xiangYing.send(`密码错误`)
	}
})
//yanZheng验证中间件
async function yanZheng(qingQiu, xiangYing, jieZhe) {
	if (qingQiu.cookies.yanZheng) {
		let yongHu = await shuJuKu.chaYongHu();
		let md5MingZi = md5(yongHu[0].mingZi);
		let md5Md5MiMa = md5(yongHu[0].miMa);
		if (qingQiu.cookies.yanZheng == md5MingZi + md5Md5MiMa) {
			jieZhe();
		} else {
			xiangYing.append('content-type', 'text/html');
			xiangYing.sendFile(path.resolve('jingTai/dengLu.html'))
		}
	} else {
		xiangYing.append('content-type', 'text/html');
		xiangYing.sendFile(path.resolve('jingTai/dengLu.html'))
	}
}
//后台页面路由
luYou.use(`/sytht`, yanZheng, houTai);

luYou.use(function(qingQiu, xiangYing) {
	xiangYing.send('404')
})

module.exports = luYou;
